<?php

require_once('dbcon.php');

function db_query($query) {
	return mysql_query($query);
}

function db_free($query) {
	mysql_free_result($query);
}

function db_query_result($query) {
	$q = db_query($query);
        if (mysql_num_rows($q) == 0) return false;
	$res = mysql_result($q,0);
	db_free($q);
	return $res;
}

function db_get_all($query) {
	$q = db_query($query);
	$res = array();
	while ($row = mysql_fetch_assoc($q)) 
		$res[] = $row;
	db_free($q);
	return $res;
}

function db_select_all($tbl_name) {
	return db_get_all("SELECT * FROM `".$tbl_name."`");
}

function db_select_all_where($tbl_name,$where) {
	return db_get_all("SELECT * FROM `".$tbl_name."` WHERE ".$where);
}

function db_escape($str) {
	return mysql_real_escape_string($str);
}

function db_select_by_id($tbl_name,$id) {
	return db_get_all("SELECT * FROM `".$tbl_name."` WHERE id = ".(int)$id);
}

function db_insert($tbl_name,$data) {
	foreach ($data as $var => $val) {
		if (!isset($cols)) {
			$cols = "`$var`";
			$data = "$val";
		} else {
			$cols .= ",`$var`";
			$data .= ",$val";
		}
	}
	db_query("INSERT INTO $tbl_name ($cols) VALUES ($data)");
}

function db_safe_insert($tbl_name,$data) {
	$new_data = array();
	foreach ($data as $var => $val) {
		$new_data[$var] = db_escape($val);
	}
	db_insert($tbl_name,$new_data);
}